package org.carabiner.infinitest;

import java.util.List;

import javax.swing.event.EventListenerList;

import org.carabiner.infinitest.TestEvent.EventType;

/**
 * 
 * @author <a href="mailto:benrady@gmail.com"Ben Rady</a>
 */
class TestRunnerEventSupport
{
  private EventListenerList listenerList;
  private Object source;

  public TestRunnerEventSupport(Object eventSource)
  {
    source = eventSource;
    listenerList = new EventListenerList();
  }

  public void addTestStatusListener(TestStatusListener listener)
  {
    listenerList.add(TestStatusListener.class, listener);
  }

  public void fireTestFailed(String testName, String message, Throwable throwable, String methodName)
  {
    TestStatusListener[] listeners = listenerList.getListeners(TestStatusListener.class);
    for (int i = listeners.length - 1; i >= 0; i -= 1)
    {
      (listeners[i]).testFailed(new TestEvent(source, TestEvent.EventType.TEST_FAILURE, message, testName, methodName, throwable));
    }
  }

  public void fireTestError(String testName, String message, Throwable throwable, String methodName)
  {
    TestStatusListener[] listeners = listenerList.getListeners(TestStatusListener.class);
    for (int i = listeners.length - 1; i >= 0; i -= 1)
    {
      (listeners[i]).testError(new TestEvent(source, TestEvent.EventType.TEST_ERROR, message, testName, methodName, throwable));
    }

  }

  public void fireTestMethodSucceeded(String testName, String methodName)
  {
    TestStatusListener[] listeners = listenerList.getListeners(TestStatusListener.class);
    for (int i = listeners.length - 1; i >= 0; i -= 1)
    {
      (listeners[i]).testMethodSucceeded(new TestEvent(source, TestEvent.EventType.METHOD_SUCCESS, "Test Succeeded", testName, methodName, null));
    }
  }

  public void fireTestCaseSucceeded(String testName)
  {
    TestEvent testEvent = new TestEvent(source, TestEvent.EventType.TEST_SUCCESS, "Test Succeeded", testName, "", null);
    fireTestEvent(testEvent);
  }

  public void fireTestEvent(TestEvent testEvent)
  {
    TestStatusListener[] listeners = listenerList.getListeners(TestStatusListener.class);
    for (int i = listeners.length - 1; i >= 0; i -= 1)
    {
      EventType type = testEvent.getType();
      if (type.equals(TestEvent.EventType.TEST_SUCCESS))
        listeners[i].testCaseSucceeded(testEvent);
      if (type.equals(TestEvent.EventType.TEST_FAILURE))
        listeners[i].testFailed(testEvent);
      if (type.equals(TestEvent.EventType.TEST_ERROR))
        listeners[i].testError(testEvent);
      if (type.equals(TestEvent.EventType.METHOD_SUCCESS))
        listeners[i].testMethodSucceeded(testEvent);
    }
  }

  public void fireTestEvents(List<TestEvent> events)
  {
    for (TestEvent event : events)
    {
      fireTestEvent(event);
    }
  }
}
